<?php

namespace app\selladmin\controller;

use app\selladmin\controller\CommonController;
use app\selladmin\model\Item;
use app\selladmin\model\Itemsimgclass;
use app\selladmin\model\Comment;
use app\util\Utils;
use think\Db;
use app\selladmin\model\Reply;
use app\util\File;
use app\selladmin\model\Itemimg;
use think\Validate;
use app\selladmin\model\Store;

class ItemController extends CommonController {
    /*
     * 项目列表
     * author xfwed 
     * date 2017.08.07
     */

    public function ItemList() {
        //$storename = input('get.store_name');
        //查询项目信息
        $item = new Item();
        $item_name = input('get.item_name');
        $itemList = $item->ItemInfo('', $item_name, 12);
        return view('itemlist', [
            'item_name' => $item_name,
            'itemList' => $itemList,
        ]);
    }

    /*
     * 项目分类
     * author xfwed
     * date 2017.08.08      
     */

    public function ItemClass() {
        $itemsimgclass = new Itemsimgclass();
        $itemclass = $itemsimgclass->ItemClass(2, '');
        return view('itemclass', [
            'itemclass' => $itemclass,
        ]);
    }

    /*
     * 项目图片库
     * author xfwed
     * date 2017.08.08      
     */

    public function ImgGallery() {
        $itemsimgclass = new Itemsimgclass();
        $itemclass = $itemsimgclass->ItemClass(3, 12);
        //将图片每4个分开
        $itemclass1 = $itemclass->toArray()['data'];
        $itemclass1 = array_chunk($itemclass1, 4);
        return view('imggallery', [
            'itemclass' => $itemclass,
            'itemclass1' => $itemclass1,
        ]);
    }

    /*
     * 项目评价列表
     * author xfwed 
     * date 2017.08.07
     */

    public function CommentList() {
        $item_id = input('get.item_id');
        //查询项目信息
        $comment = new Comment();
        $commentList = $comment->CommentList('', '', '', '', $item_id, 6);
        for ($i = 0; $i < count($commentList); $i++) {
            $reply = Reply::where('comment_id=' . $commentList[$i]['id'])->field('content,add_time')->find();
            $commentList[$i]['rcontent'] = $reply['content'];
            $commentList[$i]['radd_time'] = $reply['add_time'];
        }
        return view('commentlist', [
            'commentList' => $commentList,
        ]);
    }

    /*
     * 添加图片库
     * author xfwed
     * date 2017.09.18
     */

    public function addImgweb() {
        if (!$_POST) {
            //查询项目分类
            $itemsimgclass = new Itemsimgclass();
            $data = $itemsimgclass->ItemClass(1, null);
            return view('addimgweb', [
                'data' => $data,
            ]);
        } else {
            $all = input('param.');
            if ($all['country'] == -1) {
                $this->error('请选择分类');
            }
            //上传图片
            $uploadFile = request()->file('img');
            if ($uploadFile) {
                //验证图片
                $file = new File();
                if (!$file->checkImg($uploadFile)) {
                    $error = $file->getError();
                    $this->error($error);
                }
            } else {
                $this->error('请选择图片');
            }
            $photo = $file->uploadImage($uploadFile, 'itemsimg/');
            $mode = config('appconfig.app_production');
            if ($mode) {
                $publicFolder = 'kkmimg';
            } else {
                $publicFolder = 'testkkmimg';
            }
            $realPhoto = $file->getImageRealPath($photo);
            $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), false, $realPhoto);

            $data['type'] = $all['user'];
            $data['pid'] = $all['city'];
            $data['name'] = $photo;
            $data['level'] = 3;
            $data['addtime'] = time();
            $add = Db::name('itemsimgclass')->insert($data);
            if ($add) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        }
    }

    /*
     * 查询二级分类
     * author xfwed
     * date 2017.09.19
     */

    public function selectclass() {
        $id = input('param.id');
        $itemclass = Itemsimgclass::where('pid=' . $id)->select();
        return Utils::ajaxReturn(0, '查询成功', $itemclass);
    }

    /*
     * 项目详情预览
     * author xfwed
     * date 2018.08.23
     */

    public function ItemPreview() {
        $item_id = input('param.id');
        $row = Item::with('itemimg')
                ->where('id', '=', $item_id)
                ->field('id,store_id, type as itype, item_type, item_name, item_price, item_prices, item_number, item_img, item_img_thumb, vip_price, new_img, people, service_time, content, sell_count,itemcnt_img')
                ->find();
        //项目评论
        $row['commentStar'] = Comment::getItemCommentStar($item_id);
        $row['commentCount'] = Comment::getItemCommentCount($item_id);
        return view('itempreview', ['data' => $row]);
    }

    /*
     * 修改项目图片
     * author xfwed
     * date 2018.08.23
     */

    public function saveItemImg() {
        //验证图片
        $file = new File();
        $uploadFile = request()->file('img');
        if (!$file->checkImg($uploadFile)) {
            $error = $file->getError();
            $this->error($error);
        }

        $id = input('param.id');
        $type = input('param.type');
        $data = Itemimg::where('id', '=', $id)->field('item_id,img item_img,img_thumb item_img_thumb')->find();

        $photo = $file->uploadImage($uploadFile, 'item/');

        //上传图片到文件服务器
        $mode = config('appconfig.app_production');
        if ($mode) {
            $publicFolder = 'kkmimg';
        } else {
            $publicFolder = 'testkkmimg';
        }
        $realPhoto = $file->getImageRealPath($photo);
        $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), true, $realPhoto);

        if ($curlPhoto) {
            if ($type == 0) {
                $result0 = Item::where('id', '=', $data['item_id'])->update(['item_img' => $curlPhoto['image'], 'item_img_thumb' => $curlPhoto['thumb']]);
                $result = Itemimg::where('id', '=', $id)->update(['img' => $curlPhoto['image'], 'img_thumb' => $curlPhoto['thumb']]);
            } else {
                $result0 = true;
                $result = Itemimg::where('id', '=', $id)->update(['img' => $curlPhoto['image'], 'img_thumb' => $curlPhoto['thumb']]);
            }
            if ($result) {
                $file->curlDeleteImage($publicFolder, $data['item_img']);
                $file->curlDeleteImage($publicFolder, $data['item_img_thumb']);
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        } else {
            $this->error('上传错误');
        }
    }

    public function ItemCntImg() {
        if (!$_POST) {
            $id = input('param.id');
            return view('itemcntimg', ['id' => $id]);
        } else {
            $id = input('param.id');
            //验证图片
            $file = new File();
            $uploadFile = request()->file('img');
            if (!$file->checkImg($uploadFile)) {
                $error = $file->getError();
                $this->error($error);
            }

            $photo = $file->uploadImage($uploadFile, 'itemcnt/');

            //上传图片到文件服务器
            $mode = config('appconfig.app_production');
            if ($mode) {
                $publicFolder = 'kkmimg';
            } else {
                $publicFolder = 'testkkmimg';
            }
            $realPhoto = $file->getImageRealPath($photo);
            $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), true, $realPhoto);

            if ($curlPhoto) {
                $result = Item::where('id', '=', $id)->update(['itemcnt_img' => $curlPhoto['image']]);
                $this->success('上传成功');
            } else {
                $this->error('上传错误');
            }
        }
    }

    /*
     * 添加项目
     * author xfwed
     * date 2018-10-16      
     */

    public function AddItem() {
        if (!$_POST) {
            $store_id = input('param.store_id');
            $itemsimgclass = new Itemsimgclass();
            $itemclass = $itemsimgclass->ItemClass(2, '');
            $newitemimg = Itemsimgclass::where('type=1')->select();
            return view('additem', ['store_id' => $store_id, 'itemclass' => $itemclass, 'newitemimg' => $newitemimg]);
        } else {
            $rule = [
                'store_id' => 'require|integer',
                'type' => 'integer|in:' . implode(',', Item::getTypeMaps()),
                'item_type' => 'require|integer',
                'item_name' => 'require|min:2|max:30',
                'item_price' => 'require|float|gt:0|elt:99999999999.99',
                'item_prices' => 'float|gt:0|elt:99999999999.99',
                'item_number' => 'integer|gt:0',
                'vip_price' => 'requireIf:type,' . Item::TYPE_3 . '|float|gt:0|elt:99999999999.99',
                'vip_count' => 'requireIf:type,' . Item::TYPE_3 . '|integer|gt:0',
                'new_img' => 'requireIf:type,' . Item::TYPE_2,
                'tejia_price' => 'requireIf:type,' . Item::TYPE_5 . '|float|gt:0|elt:99999999999.99',
                'tejia_tag' => 'requireIf:type,' . Item::TYPE_5 . '|max:100',
                'people' => 'require|max:100',
                'service_time' => 'require|integer|gt:0',
                'content' => 'require|max:1000',
            ];
            $msg = [
                'store_id.require' => '店铺编号必须',
                'store_id.integer' => '店铺编号为数字',
                'type.integer' => '项目类型必须',
                'type.in' => '项目类型为0/1/2/3/4/5',
                'item_type.require' => '用途分类必须',
                'item_type.integer' => '用途分类为数字',
                'item_name.require' => '项目名称必须',
                'item_name.min' => '项目名称最小2',
                'item_name.max' => '项目名称最大30',
                'item_price.require' => '项目单价必须',
                'item_price.float' => '项目单价为数字',
                'item_price.gt' => '项目单价大于0',
                'item_price.elt' => '项目单价最大99999999999.99',
                'item_prices.float' => '项目疗程价为数字',
                'item_prices.gt' => '项目疗程价大于0',
                'item_prices.elt' => '项目疗程价最大99999999999.99',
                'item_number.integer' => '疗程包含次数为数字',
                'item_number.gt' => '疗程包含次数大于0',
                'vip_price.requireIf' => '会员特惠价必须',
                'vip_price.float' => '会员特惠价为数字',
                'vip_price.gt' => '会员特惠价大于0',
                'vip_price.elt' => '会员特惠价最大99999999999.99',
                'vip_count.requireIf' => '会员特惠限购数量必须',
                'vip_count.integer' => '会员特惠限购数量为数字',
                'vip_count.gt' => '会员特惠限购数量大于0',
                'new_img.requireIf' => '新项目广告图必须',
                'tejia_price.requireIf' => '特价必须',
                'tejia_price.float' => '特价为数字',
                'tejia_price.gt' => '特价大于0',
                'tejia_price.elt' => '特价最大99999999999.99',
                'tejia_tag.requireIf' => '特价标签必须',
                'tejia_tag.max' => '特价标签最大100',
                'people.require' => '适用人群必须',
                'people.max' => '适用人群最大100',
                'service_time.require' => '服务时长必须',
                'service_time.integer' => '服务时长为数字',
                'service_time.gt' => '服务时长大于0',
                'content.require' => '项目内容必须',
                'content.max' => '项目内容最大1000',
            ];

            $all = input('param.');

            $validate = new Validate($rule, $msg);
            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }

            $item_prices = 0.00;
            $item_number = 0;
            if (isset($all['item_prices']) && floatval($all['item_prices']) > 0) {
                if (isset($all['item_number'])) {
                    $item_prices = $all['item_prices'];
                    $item_number = $all['item_number'];
                } else {
                    $this->error('请输入疗程包含次数');
                }
            }
            if (isset($all['item_number']) && intval($all['item_number']) > 0) {
                if (isset($all['item_prices'])) {
                    $item_prices = $all['item_prices'];
                    $item_number = $all['item_number'];
                } else {
                    $this->error('请输入项目疗程价');
                }
            }

            $file = new File();
            $itemimgIndex = -1;
            $itemimgFiles = [];
            for ($i = 0; $i < Item::IMG_NUMBER; $i++) {
                $itemimgFile = request()->file('item_img_' . $i);
                if (!is_null($itemimgFile)) {
                    /*
                      if (!$itemimgFile->checkSize(1048576)) {
                      $itemimgIndex = $i;
                      }
                     */

                    array_push($itemimgFiles, $itemimgFile);
                }
            }
            if (count($itemimgFiles) == 0) {
                $this->error('项目图片必须');
            }
            /*
              if ($itemimgIndex != -1) {
              //return Utils::ajaxReturn(120015, '图片太大啦，上传失败', null);
              }
             */

            $store_id = $all['store_id'];
            $type = $all['type'];
            $item_type = $all['item_type'];
            $item_name = trim($all['item_name']);
            $item_price = $all['item_price'];
            $vip_price = 0.00;
            $vip_count = 0;
            if ($type == Item::TYPE_3) {
                $vip_price = $all['vip_price'];
                $vip_count = $all['vip_count'];
            }
            $new_img = null;
            if ($type == Item::TYPE_2) {
                $new_img = $all['new_img'];
            }
            $tejia_price = 0.00;
            $tejia_tag = null;
            if ($type == Item::TYPE_5) {
                $tejia_price = $all['tejia_price'];
                $tejia_tag = $all['tejia_tag'];
            }
            $people = $all['people'];
            $service_time = $all['service_time'];
            $content = $all['content'];

            //判断敏感字
            $pos = strpos($item_name, '艾灸');
            if ($pos !== false) {
                $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
            }
            $pos = strpos($item_name, '拔罐');
            if ($pos !== false) {
                $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
            }
            $pos = strpos($item_name, '洗浴');
            if ($pos !== false) {
                $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
            }
            $pos = strpos($item_name, '保健');
            if ($pos !== false) {
                $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
            }

            //上传图片
            $imgArray = $file->uploadMutilImage($itemimgFiles, 'item/', $store_id);
            foreach ($imgArray as $key => $value) {
                $extension = pathinfo($value, PATHINFO_EXTENSION);
                if ($extension == '0') {
                    //安卓上传的缓存图片后缀为0，修改为jpg
                    $oldname = $value;

                    $valueArray = explode('.', $value);
                    $valueArray[1] = 'jpg';

                    $value = implode('.', $valueArray);
                    $imgArray[$key] = $value;

                    $newname = $value;

                    $file->renameImg($oldname, $newname);
                }
            }
            //$thumbArray = $file->thumbMutilImage($imgArray);
            //上传图片到文件服务器
            $mode = config('appconfig.app_production');
            if ($mode) {
                $publicFolder = 'kkmimg';
            } else {
                $publicFolder = 'testkkmimg';
            }
            $folder = pathinfo($imgArray[0], PATHINFO_DIRNAME);
            $imgRealArray = $file->getMutilImageRealPath($imgArray);
            $curlUploadResult = $file->curlUploadMutilImage($publicFolder, $folder, true, $imgRealArray);
            if (!$curlUploadResult) {
                $this->error('图片上传失败');
            }

            $curlImgArray = $curlUploadResult['image'];
            $curlThumbArray = $curlUploadResult['thumb'];

            //上传项目详情图
            $uploadFile = request()->file('img');
            if (!is_null($uploadFile)) {
                if (!$file->checkImg($uploadFile)) {
                    $error = $file->getError();
                    $this->error($error);
                }

                $photo = $file->uploadImage($uploadFile, 'itemcnt/');

                //上传图片到文件服务器
                $mode = config('appconfig.app_production');
                if ($mode) {
                    $publicFolder = 'kkmimg';
                } else {
                    $publicFolder = 'testkkmimg';
                }
                $realPhoto = $file->getImageRealPath($photo);
                $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), true, $realPhoto);
                if ($curlPhoto) {
                    $itemcnt_img = $curlPhoto['image'];
                } else {
                    $itemcnt_img = '';
                }
            }  else {
                $itemcnt_img = '';
            }

            Db::startTrans();

            $data = [
                'store_id' => $store_id,
                'type' => $type,
                'item_type' => $item_type,
                'item_name' => $item_name,
                'item_price' => $item_price,
                'item_prices' => $item_prices,
                'item_number' => $item_number,
                'item_img' => $curlImgArray[0],
                'item_img_thumb' => $curlThumbArray[0],
                'vip_price' => $vip_price,
                'vip_count' => $vip_count,
                'new_img' => $new_img,
                'tejia_price' => $tejia_price,
                'tejia_tag' => $tejia_tag,
                'people' => $people,
                'service_time' => $service_time,
                'content' => $content,
                'add_time' => time(),
                'update_time' => time(),
                'itemcnt_img' => $itemcnt_img,
            ];
            $insertId = Item::insertGetId($data);

            $imgData = [];
            foreach ($curlImgArray as $key => $value) {
                $oneData = [
                    'item_id' => $insertId,
                    'itemsimgclass_id' => 0,
                    'img' => $value,
                    'img_thumb' => $curlThumbArray[$key],
                ];

                array_push($imgData, $oneData);
            }
            $imgResult = Itemimg::insertAll($imgData);

            if ($insertId && $imgResult) {
                Db::commit();

                Store::updateInWxapp($store_id);
                $this->success('项目添加成功');
            } else {
                Db::rollback();
                $this->error('项目添加失败');
            }
        }
    }

    /*
     * 保存项目
     * 作者 xfwed
     * 日期 2018-10-16
     */

    public function saveItem() {
        $rule = [
            'item_id' => 'require|integer',
            'item_name' => 'require|min:2|max:30',
            'item_price' => 'require|float|gt:0|elt:99999999999.99',
            'item_prices' => 'float|gt:0|elt:99999999999.99',
            'item_number' => 'integer|gt:0',
            'people' => 'require|max:100',
            'service_time' => 'require|integer|gt:0',
            'content' => 'require|max:1000',
        ];
        $msg = [
            'item_id.require' => '项目编号必须',
            'item_id.integer' => '项目编号为数字',
            'item_name.require' => '项目名称必须',
            'item_name.min' => '项目名称最小2',
            'item_name.max' => '项目名称最大30',
            'item_price.require' => '项目单价必须',
            'item_price.float' => '项目单价为数字',
            'item_price.gt' => '项目单价大于0',
            'item_price.elt' => '项目单价最大99999999999.99',
            'item_prices.float' => '项目疗程价为数字',
            'item_prices.gt' => '项目疗程价大于0',
            'item_prices.elt' => '项目疗程价最大99999999999.99',
            'item_number.integer' => '疗程包含次数为数字',
            'item_number.gt' => '疗程包含次数大于0',
            'people.require' => '适用人群必须',
            'people.max' => '适用人群最大100',
            'service_time.require' => '服务时长必须',
            'service_time.integer' => '服务时长为数字',
            'service_time.gt' => '服务时长大于0',
            'content.require' => '项目内容必须',
            'content.max' => '项目内容最大1000',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            $this->error($error);
        }

        $item_prices = 0.00;
        $item_number = 0;
        if (isset($all['item_prices']) && floatval($all['item_prices']) > 0) {
            if (isset($all['item_number'])) {
                $item_prices = $all['item_prices'];
                $item_number = $all['item_number'];
            } else {
                $this->error('请输入疗程包含次数');
            }
        }
        if (isset($all['item_number']) && intval($all['item_number']) > 0) {
            if (isset($all['item_prices'])) {
                $item_prices = $all['item_prices'];
                $item_number = $all['item_number'];
            } else {
                $this->error('请输入项目疗程价');
            }
        }

        $item_id = $all['item_id'];
        $item_name = trim($all['item_name']);
        $item_price = $all['item_price'];
        $people = $all['people'];
        $service_time = $all['service_time'];
        $content = $all['content'];

        //判断敏感字
        $pos = strpos($item_name, '艾灸');
        if ($pos !== false) {
            $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
        }
        $pos = strpos($item_name, '拔罐');
        if ($pos !== false) {
            $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
        }
        $pos = strpos($item_name, '洗浴');
        if ($pos !== false) {
            $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
        }
        $pos = strpos($item_name, '保健');
        if ($pos !== false) {
            $this->error('项目名称不能包含艾灸、拔罐、洗浴、保健等词汇');
        }

        Db::startTrans();

        $data = [
            'item_name' => $item_name,
            'item_price' => $item_price,
            'item_prices' => $item_prices,
            'item_number' => $item_number,
            'people' => $people,
            'service_time' => $service_time,
            'content' => $content,
            'update_time' => time(),
        ];
        $itemResult = Item::where('id', '=', $item_id)->update($data);

        if ($itemResult) {
            Db::commit();
            $this->success('项目修改成功');
        } else {
            Db::rollback();
            $this->error('项目修改失败');
        }
    }

}
